//
//  WBMainController.swift
//  simpleWeibo


import UIKit
import SVProgressHUD

class WBMainController: UITabBarController {
    
    fileprivate lazy var composeButton: UIButton = UIButton.cz_imageButton(
        "tabbar_compose_icon_add",
        backgroundImageName: "tabbar_compose_button")
    fileprivate var timer: Timer?
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupChildControllers()
        setupComposeButton()
        setupTimer()
        setupNewFeatureViews()
        
        delegate = self
        NotificationCenter.default.addObserver(self, selector: #selector(userLogin), name: NSNotification.Name(rawValue: WBUserShouldLoginNotification), object: nil)
    }
    
    deinit {
        timer?.invalidate()
        NotificationCenter.default.removeObserver(self)
    }
    
    //撰写微博
    @objc fileprivate func didClickComposeButton() {
        //FIXME 0 判断是否登录
        
        //1 实例化视图
        let v = WBComposeTypeView.composeTypeView()
        
        //2 显示视图
        // [weak v] v在闭包里 弱引用 处理循环引用问题
        v.show {[weak v] (clsName) in
            guard let clsName = clsName, let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? UIViewController.Type else {
                return
            }
            let vc = cls.init()
            let nav = UINavigationController(rootViewController: vc)
            self.present(nav, animated: true, completion: {
                v?.removeFromSuperview()
            })
        }
    }
    
    @objc fileprivate func userLogin(n: Notification) {
        print("用户登录通知 \(n)")
        var when = DispatchTime.now()
        if n.object != nil {
            SVProgressHUD.setDefaultMaskType(.gradient)
            SVProgressHUD.showInfo(withStatus: "用户登录已经超时, 需要重新登录")
            when = DispatchTime.now() + 2
        }
        DispatchQueue.main.asyncAfter(deadline: when) {
            SVProgressHUD.setDefaultMaskType(.clear)
            let Nav = UINavigationController.init(rootViewController: WBOAuthViewController())
            self.present(Nav, animated: true, completion: nil)
        }
    }
    
}

// MARK: - 新特性视图处理
extension WBMainController {
    func setupNewFeatureViews() {
        //1 如果更新 显示新特性 否则显示欢迎
        let v = isNewVervison ? WBNewFeatureView.newFeatureView() : WBWelcomeView.welcomeView()
//        v.frame = view.bounds
        
        //2 添加视图
        view.addSubview(v)
    }
    
    /// extension 中可以有计算型属性 不会占用存储空间
    /// 构造函数: 给属性分配空间
    private var isNewVervison : Bool {
        //1 取当前的版本号 1.0.2
//        print(Bundle.main.infoDictionary ?? [String : AnyObject]())
        let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? ""
        print(currentVersion)
        //2 取保存在 Document(iTunes备份) [最理想保存在用户偏好] 目录中的之前版本号
        let path: String = ("version" as NSString).cz_appendDocumentDir()
        let sandboxVersion = try? String(contentsOfFile: path) 
        print(sandboxVersion ?? "")
        
        //3 保存当前版本号 在沙盒
        try? currentVersion.write(toFile: path, atomically: true, encoding: .utf8)
        
        //4 比较两个版本号 是否一致
        return currentVersion != sandboxVersion
        //调试新特性界面
//        return currentVersion == sandboxVersion
    }
    
}

// MARK: - UITabBarControllerDelegate
extension WBMainController: UITabBarControllerDelegate {
    func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
        print("将要调整的控制器 \(viewController)")
        
        //1 获取控制器在数组中的索引
        let idx = (children as NSArray).index(of: viewController)
        
        //2 判断当前索引是首页 同事idx 也是首页  重复点击首页的按钮
        if selectedIndex == 0 && idx == selectedIndex {
            //3 让表格滚动到顶部
            //a) 获取到控制器
            let nav = children[0] as! UINavigationController
            let vc = nav.children[0] as! WBHomeViewController
            
            //b) 滚动到顶部
            vc.tableView?.setContentOffset(CGPoint(x: 0, y: 0), animated: true)
            
            //4 刷新数据 增加延迟 是保证表格先滚动到顶部再刷新
            DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                vc.loadData()
            }
            
            //5 tabItem 数字消掉 为nil app角标为0
            vc.tabBarItem.badgeValue = nil
            
            UIApplication.shared.applicationIconBadgeNumber = 0
        }
        
        return !viewController.isMember(of: UIViewController.self)
//        return true
    }
}

// MARK: - 计时器相关
extension WBMainController {
    func setupTimer() {
        timer = Timer.scheduledTimer(timeInterval: 6.0, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
        
    }
    
    /// 触发方法
    @objc private func updateTimer() {
        if !WBNetWorkManager.shared.userLogon {
            return
        }
        
        print(#function)
        WBNetWorkManager.shared.unreadCount { (count) in
            print("未读消息数为: \(count)")
            self.tabBar.items?[0].badgeValue = (count > 0 ? "\(count)" : nil)
            UIApplication.shared.applicationIconBadgeNumber = 3;
        }
    }
}

// extension 类似于 OC 中的 分类，在 Swift 中还可以用来切分代码块
// 可以把相近功能的函数，放在一个 extension 中
// 便于代码维护
// 注意：和 OC 的分类一样，extension 中不能定义属性
// MARK: - 设置界面
extension WBMainController {
    
    /// 设置所有子控制器
    fileprivate func setupChildControllers() {
        //拿出沙盒里从网络加载的数据 Data
        let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
        let jsonPath = (docDir as NSString).appendingPathComponent("net.json")
        var data = NSData(contentsOfFile: jsonPath)
        //如果为空, 使用bundle里的main.json 数据
        if data == nil {
            let path = Bundle.main.path(forResource: "main.json", ofType: nil)
            data = NSData(contentsOfFile: path!)
        }
        
        //Data 反序列化 -> 数组
        guard let array = try? JSONSerialization.jsonObject(with: data! as Data, options: []) as? [[String : AnyObject]]
            else {
                return
        }
        
        var arrayM = [UIViewController]()
        for dict in array {
            let vc = controller(dict: dict as [String : AnyObject])
            arrayM.append(vc)
        }
        viewControllers = arrayM
    }
    
    private func controller(dict: [String: AnyObject]) -> UIViewController {
        //1取得字典内容
        guard let clsName = dict["clsName"] as? String,
            let title = dict["title"] as? String,
            let imageName = dict["imageName"] as? String,
            let cls = NSClassFromString(Bundle.main.namespace + "." + clsName) as? WBBaseController.Type,
            let visitorInfo = dict["visitorInfo"] as? [String : String]
        
            else {
                let vc = UIViewController()
                vc.view.backgroundColor = UIColor.yellow
                
                return vc
        }
        
        //2创建控制器
        let vc = cls.init()
        vc.visitorInfoDic = visitorInfo
        vc.title = title
        
        //3设置 tabBar图像
        vc.tabBarItem.image = UIImage(named: "tabbar_" + imageName)
        vc.tabBarItem.selectedImage = UIImage(named: "tabbar_" + imageName + "_selected")?.withRenderingMode(.alwaysOriginal)
        
        //4设置tabBar的标题字体
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange],
                                             for: .highlighted)
        vc.tabBarItem.setTitleTextAttributes([NSAttributedString.Key.font: UIFont.systemFont(ofSize: 12)],
                                             for: .normal)
        
        // 实例化导航控制器的时候 会调用push方法 将rootVC 压栈
        let nav = WBNavigationController.init(rootViewController: vc)
        
        return nav
        
    }
    
    fileprivate func setupComposeButton() {
        tabBar.addSubview(composeButton)
        composeButton.addTarget(self, action: #selector(didClickComposeButton), for: .touchUpInside)
        //计算按钮的宽度
        let count: CGFloat = CGFloat(children.count)
        let composeButtonWidth = tabBar.frame.size.width / count
        //CGRectInset 正数向内缩进, 负数向外拓展, 盖住容错点
        composeButton.frame = tabBar.bounds.insetBy(dx: composeButtonWidth * 2, dy: 0)
        
        
    }
    
}


